/*
 * @Date: 2024-02-26 19:43:48
 * @LastEditors: lyx
 * @LastEditTime: 2024-03-08 09:18:34
 * @FilePath: \taro-template3\src\utils\request.ts
 * @Description:
 */
import { loginout } from "@/lib/auth";
import { fetchRefreshToken } from "@/pages/index/services";
import Taro from "@tarojs/taro";

// 内网
export const chat_baseUrl = "http://gpt-demo2.supcon5t.com:31722";
export const app_baseUrl = "http://gpt-demo2.supcon5t.com:31723";
// 外网
// const chat_baseUrl = "https://supobp.supcon5t.com:30021/open-api/gpt/industry-gpt"
// const app_baseUrl = "https://supobp.supcon5t.com:30021/open-api/gpt/industry-gpt"

const default_header = {
  "Content-Type": "application/json",
};

interface IRequestOptions {
  method: keyof Taro.request.Method;
  url: string;
  data?: any;
  header?: any;
  type?: "chat" | "app";
}

const BASE_URL_MAP = {
  chat: chat_baseUrl,
  app: app_baseUrl,
};
export const REQ_FAIL_ERROR_MSG = {
  abort: "request:fail abort",
  timeout: "request:fail timeout",
};

export const Request = (
  options: IRequestOptions = {
    type: "chat",
    method: "GET",
    url: "",
    data: {},
    header: {},
  }
) => {
  console.log("options", options);
  let tokenId = Taro.getStorageSync("token");
  return Taro.request({
    url: BASE_URL_MAP[options.type || "chat"] + options.url,
    method: options.method,
    data: {
      ...options.data,
    },
    header: {
      ...default_header,
      ...options.header,
      // Trust 为 远端通用校验, 接入用户后需要改为登录token
      Authorization: tokenId || "Trust admin",
    },
  }).then(async (res) => {
    const { statusCode, data } = res;
    if (statusCode >= 200 && statusCode < 300) {
      const { code } = data;
      if (code === "A0230") {
        const reRes: any = await fetchRefreshToken();
        if (reRes) {
          Taro.getCurrentInstance()?.page?.onLoad?.({});
        } else {
          loginout();
        }
      }
      // TODO: 错误提示是否需要这里处理?
      // const { code, success, msg } = data;
      // if (!success) {
      //   Taro.showToast({
      //     title: msg,
      //     icon: "none",
      //     mask: true,
      //   });
      // }
      return data;
    } else {
      throw new Error(`网络请求错误，状态码${statusCode}`);
    }
  });
};
